<?php
namespace app\controller;
use app\BaseController;
use think\facade\Db;
use app\model\UserModel;
use think\facade\Request;

class Rank extends BaseController
{
    public function index()
    {
        return $this->request->action() . '<br />' . $this->app->getBasePath() . '<br />用户';
    }
    public function get()
    {
        if ($this->request->isGet()) {
            $data = Db::table("rank")->select();
            return json($data);
        }
    }

    public function salaryget()
    {
        if ($this->request->isGet()) {
            $data = Db::table("rank")->select();
            $dataArr = array();
            $dataCode = 200;
            foreach ($data as $item) {

                $start_date = strtotime($item['hiredate']);
                $now = time();
                $years = floor(($now - $start_date) / (365 * 24 * 60 * 60));
                $rank = $years*50+$item['rank'];
                $dataArr[]=[
                    "name"=>$item['name'],
                    "rank"=>$rank,
                    "hiredate"=>$years

                ];
            }
            return json($dataArr);
        }
    }

    public function add()
    {
        if ($this->request->isPost()) {

            $data = $this->request->post();
//            return json($data);
            if (empty($data['name']) || empty($data['rank']) || empty($data['hiredate']) ) {
                // 数据验证失败，返回错误信息
                return json(['code' => 0, 'msg' => '添加失败 缺少信息']);
            }

            // ... 数据验证代码 ...
            $GetData = [
                "name"=>$data['name'],
                "rank"=>$data['rank'],
                "hiredate"=>$data['hiredate']
            ];

            // 如果数据验证通过，将数据保存到数据库
            $userModel = new UserModel();
            $result =$userModel->checkAndSaveUser($GetData);

            if ($result) {
                // 保存到数据库成功，返回成功信息
                return json(['code' => 0, 'msg' => '添加成功','data' => $GetData]);
            } else {
                // 保存到数据库失败，返回错误信息
                return json(['code' => 1, 'msg' => '保存到数据库失败','data' => $result]);
            }
        }

    }

}